package cn.kzgg.ymcc.service.impl;

import cn.kzgg.ymcc.Exception.GlobleException;
import cn.kzgg.ymcc.domain.AlipayInfo;
import cn.kzgg.ymcc.domain.PayOrder;
import cn.kzgg.ymcc.dto.AlipayNotifyDto;
import cn.kzgg.ymcc.dto.PayApplyDto;
import cn.kzgg.ymcc.mapper.PayOrderMapper;
import cn.kzgg.ymcc.service.IAlipayInfoService;
import cn.kzgg.ymcc.service.IPayOrderService;
import cn.kzgg.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.page.Client;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import dto.PayNotifyDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kzgg
 * @since 2022-07-31
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 拿到订单号
     *
     * @param orderNo
     * @return
     */
    @Override
    public PayOrder selectByOrderNo(String orderNo) {

        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        return selectOne(wrapper);
    }

    /**
     * 1.参数空校验  JSR303
     * 2.业务校验  根据订单号查询支付单
     * 2.1 校验支付单的状态是否是待支付，如果不是，---不能发起支付（重复支付）
     * 2.2 不同的支付方式，不同的支付接口
     * <p>
     * 3.触发支付
     * 4.将支付的响应结果返回
     *
     * @param dto
     * @return
     */
    @Override
    public String apply(PayApplyDto dto) {
        //业务校验  根据订单号查询支付单
        PayOrder payOrder = selectByOrderNo(dto.getOrderNo());
        AssertUtil.isNotNull(payOrder, "订单号不存在，发起支付失败");
        //校验支付单的状态是否是待支付
        boolean wait = payOrder.getPayStatus() == PayOrder.STATE_WAIT_PAY;
        AssertUtil.isTrue(wait, "重复支付！，发起支付失败");
        //触发支付
        if (payOrder.getPayType() == 1) {
            //支付宝支付
            return Alipay(payOrder, dto);
        } else if (payOrder.getPayType() == 2) {
            //微信支付。。。
        }
        return null;
    }


    public String Alipay(PayOrder payOrder, PayApplyDto dto) {
        AlipayInfo alipayInfo = alipayInfoService.selectOne(null);
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions(alipayInfo));
        try {
            // 2. 网页端支付
            Client page = Factory.Payment.Page();
            AlipayTradePagePayResponse response = page.pay(
                    payOrder.getSubject(),
                    payOrder.getOrderNo(),
                    payOrder.getAmount().toString(),
                    StringUtils.isEmpty(dto.getCallUrl()) ? alipayInfo.getReturnUrl() : dto.getCallUrl()//同步回调地址
            );
            System.out.println(response.getBody());

            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
                //返回前端form表单
                return response.getBody();
            } else {
                System.out.println("调用失败，原因：");
                throw new GlobleException("支付调用失败！！！");
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public Config getOptions(AlipayInfo alipayInfo) {
        Config config = new Config();
        config.protocol = alipayInfo.getProtocol();
        //沙箱API地址
        config.gatewayHost = alipayInfo.getGatewayHost();
        config.signType = alipayInfo.getSignType();
        config.appId = alipayInfo.getAppId();
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = alipayInfo.getMerchantPrivateKey();
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = alipayInfo.getAlipayPublicKey();
        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = alipayInfo.getNotifyUrl();
        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        config.encryptKey = "";
        return config;
    }


    /**
     * 处理支付成功之后的异步回调逻辑
     *
     * @param dto
     * @return
     */
    @Override
    public String notify(AlipayNotifyDto dto) throws Exception {
        // 收到了支付宝的异步通知
        // 1.需要校验身份
        String jsonString = JSON.toJSONString(dto);
        Map<String, String> dtoMap = JSONObject.parseObject(jsonString, Map.class);
        //接收到的所有参数放入一个Map中
        Boolean isValid = Factory.Payment.Common().verifyNotify(dtoMap);
        if (!isValid) {
            // 有可能信息被篡改，需要支付宝重新通知
            return "Fail";
        }
        // 2.校验是否是我们的订单
        PayOrder payOrder = selectByOrderNo(dto.getOut_trade_no());
        if (payOrder == null) {
            return "Fail";
        }
        //如果支付单已经被取消，但是支付宝支付成功的消息回来了
        if (payOrder.getPayStatus() == PayOrder.STATE_CANCEL) {
            try {
                log.info("调用支付宝退款！！");
                //调用退款
                AlipayTradeRefundResponse refund = Factory.Payment.Common()
                        .refund(payOrder.getOrderNo(), payOrder.getAmount().toString());
            } catch (Exception e) {
                e.printStackTrace();
                /**
                 * 做兜底
                 * 2.保存要取消支付单的记录到数据库，运维人员来人工跟进
                 * 3.给运维人员发站内信，邮件，消息---- 对接钉钉推销
                 */
            }
            return "success";
        }
        if (payOrder.getPayStatus() != PayOrder.STATE_WAIT_PAY) {
            return "Fail";
        }
        String trade_status = dto.getTrade_status();
        if (!trade_status.equals(AlipayNotifyDto.TRADE_SUCCESS)) {
            return "Fail";
        }

//处理支付成功之后的业务逻辑=============================================
        //1.修改支付单状态
        payOrder.setPayStatus(PayOrder.STATE_PAY_SUCCESS);
        payOrder.setUpdateTime(new Date());
        //updateById(payOrder); 不能在这里改，应该交给事务监听器，在事务监听器中执行本地事务
        //=============================================
        // 发布事务消息  消息体需要字段： 订单号   购买人   课程id
        PayNotifyDto payNotifyDto = new PayNotifyDto(
                payOrder.getOrderNo(),
                payOrder.getExtParams()
        );

        log.info("发送支付成功通知事务消息");
        //构建消息体
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(payNotifyDto)).build();
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
                "service-pay-tx-group",//要和监听器上注解申明的名字一致
                "pay-notify-topic:pay-notify-tag",
                message,  //消息体
                payOrder   //额外参数
        );
        log.info("发送完支付异步通知事务消息--检查事务消息状态");
        LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
        SendStatus sendStatus = transactionSendResult.getSendStatus();
        if (localTransactionState != LocalTransactionState.COMMIT_MESSAGE || sendStatus != SendStatus.SEND_OK) {
            log.info("校验发送事务消息状态异常");
            throw new GlobleException("处理支付成功结果失败！！");
        }
        //2.修改订单状态
        //3.添加用户的课程购买记录
        return "success";
    }

    /**
     * 支付超时
     * 1.取消支付单
     * 2.调用支付宝，关闭支付
     * 。在登录页面，是可以关闭交易的
     * 。如果到了支付页面，输入了支付密码，点击支付之后，那么关闭关闭不了
     * --- 降级方案，在支付宝的异步通知中：走退款逻辑---
     *
     * @param orderNo
     */
    @Override
    public void cancelOrder(String orderNo) {
        PayOrder payOrder = selectByOrderNo(orderNo);
        //取消支付单
        if (payOrder.getPayStatus().intValue() == PayOrder.STATE_WAIT_PAY) {
            payOrder.setPayStatus(PayOrder.STATE_CANCEL);
            updateById(payOrder);
        }
        //调用支付宝，关闭支付
        try {
            AlipayTradeCloseResponse close = Factory.Payment.Common().close(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
